package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;

import utils.ItemsHelper;
import entities.Item;

/**
 * Servlet implementation class ItemServlet
 */
@WebServlet("/NewItems")
public class NewItemsServlet extends HttpServlet {
	/**
	 * number of items to show 
	 */
	private static final int NEW_ITEMS_IN_PAGE = 4;
	private static final String ITEMS = "items";
	private static final long serialVersionUID = 1L;
	

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Timestamp ts = ServletsUtil.getStartFrom(request, response);
	//	response.setContentType("text/json");
		response.setStatus(200);
		//response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
		List<Item> itemsList = ItemsHelper.getNewItems(NEW_ITEMS_IN_PAGE, ts);
		System.out.println(this.getServletName() + ":" + ts);
		ItemsHelper.isUsersItem(itemsList,ServletsUtil.getUserID(request));
			ObjectMapper mapper = new ObjectMapper();
			PrintWriter writer = response.getWriter();
			writer.write(
						"{\"" + ITEMS +"\":" + mapper.writeValueAsString(itemsList) + "}"					
						);
			writer.flush();
	}


}
